<template>
  <a-form
      layout="inline"
      :model="formState"
      @finish="handleFinish"
      style="margin-bottom: 25px"
  >
    <a-form-item v-if="isPermission('leader')">
      <a-select v-model:value="formState.employeeLeaderId" @change="changeLeader" allowClear style="width: 250px"
                :placeholder="$t('客服组长')">
        <a-select-option v-for="item in leaderList" :key="item.systemId" :value="item.systemId">
          {{ item.systemName }}
        </a-select-option>
      </a-select>
    </a-form-item>
    <a-form-item v-if="isPermission('user')">
      <a-select v-model:value="formState.employeeId" allowClear style="width: 250px" :placeholder="$t('客服')">
        <a-select-option v-for="item in systemUserList" :key="item.id" :value="item.id">{{
            item.name
          }}
        </a-select-option>
      </a-select>
    </a-form-item>
    <a-form-item v-if="isPermission('user')">
      <a-button
          type="primary"
          html-type="submit"
      >
        {{ $t('查询') }}
      </a-button>
    </a-form-item>
  </a-form>
    <a-row  :gutter="16">
      <a-col :md="6" :xs="24" >
        <a-card class="charts_item" :title="$t('待完成订单')  + ': '  + orderTotal.todoNum " :bordered="false">
          <div>
            <span style="margin-right: 15px">{{ $t('待办列表') }}: {{ orderTotal.backlogNum }}</span>
            <span>{{ $t('重点待办') }}: {{ orderTotal.emphasisNum }}</span>
          </div>
          <div id="order_charts1" class="order_charts"></div>
        </a-card>
      </a-col>

      <a-col :md="6"  :xs="24" >
        <a-card class="charts_item" :title="$t('已关闭订单')+ ': '  + orderTotal.closeNum " :bordered="false">
          <div id="order_charts2" class="order_charts" style="margin-top:22px"></div>
        </a-card>
      </a-col>
      <a-col :md="6" :xs="24">
        <a-card class="charts_item" :title="$t('总订单数')+ ': '  + orderTotal.totalNum " :bordered="false">
          <div id="order_charts3" class="order_charts" style="margin-top:22px"></div>
        </a-card>
      </a-col>
      <a-col :md="6" :xs="24">
        <a-card class="charts_item" :title="$t('日目标达成率')" :bordered="false">
          <div id="order_charts4" class="order_charts" style="margin-top:22px"></div>
        </a-card>
      </a-col>
    </a-row>
  <a-card
      style="width: 100%;margin-top:20px"
      :tab-list="collectionTabList"
      :active-tab-key="collectionActiveKey"
      @tabChange="key => collectionChange(key)"
  >
    <template #title>
      <span>{{ $t('收款笔数') + ': ' }}</span> {{ collectionTableData.length > 0 ? collectionTableData[0].proceedsTotalNum : '' }} ({{$t('来自个订单',{num:collectionTableData.length > 0 ? collectionTableData[0].orderNum : ''})}})
    </template>
    <template #customRender="item">
      <span>
        {{ item.title }}
      </span>
    </template>
    <a-table :columns="collectionTableColumn" :pagination="false" :data-source="collectionTableData"
             :scroll="{x:1000}" bordered>
    </a-table>
  </a-card>
  <a-card
      style="width: 100%;margin-top:20px"
      :tab-list="collectionTabList"
      :active-tab-key="amountActiveKey"
      @tabChange="key => amountChange(key)"
  >
    <template #title>
      <span>{{ $t('收款金额 ') + ': ' }}</span>
      {{ amountTableData.length > 0 ? amountTableData[0].proceedsTotalFee : '' }} ({{$t('含已提现打款金额') }}: {{amountTableData.length > 0 ? amountTableData[0].orderFee : ''}})
    </template>
    <template #customRender="item">
      <span>
        {{ item.title }}
      </span>
    </template>
    <a-table :columns="amountTableColumn" :pagination="false" :data-source="amountTableData"
             :scroll="{x:1000}" bordered>
    </a-table>
  </a-card>
</template>

<script>
import * as echarts from 'echarts/core';
import {fetchIncomeHistory, fetchIncomeToday, fetchInsertHistory, fetchInsertToday, fetchOrderNum} from '@/api/index'
import {onBeforeUnmount, onMounted, reactive, ref, toRefs} from "vue";
import locale from '@/locale'
import {selectLeader} from "../../api/authority";
import {selectHomeSystemUser} from "../../api";
  import {hasPermission} from '@/utils'

const {t} = locale.global;
const collectionTabList = [
  {
    key: 'today',
    title: t('今日新增收款'),
    slots: {
      tab: 'customRender',
    },
  },
  {
    key: 'history',
    title: t('库存收款'),
    slots: {
      tab: 'customRender',
    },
  },
];

const collectionTableColumn = [
  {title: t('合计'), dataIndex: 'proceedsTodayNum', width: 150, align: 'center',},
  {title: t('保证金笔数'), dataIndex: 'paymentNum', width: 150, align: 'center'},
  {title: t('解冻费笔数'), dataIndex: 'thawNum', width: 150, align: 'center'},
  {title: t('事故处理费笔数'), dataIndex: 'accidentNum', width: 150, align: 'center'},
  {title: t('插队费笔数'), dataIndex: 'jumpNum', width: 150, align: 'center'},
]
const amountTableColumn = [
  {title: t('合计'), dataIndex: 'proceedsTodayFee', width: 150, align: 'center',},
  {title: t('保证金'), dataIndex: 'paymentFee', width: 150, align: 'center'},
  {title: t('解冻费'), dataIndex: 'thawFee', width: 150, align: 'center'},
  {title: t('事故处理费'), dataIndex: 'accidentFee', width: 150, align: 'center'},
  {title: t('插队费'), dataIndex: 'jumpFee', width: 150, align: 'center'},
]
export default {
  name: "Index",
  setup() {
    const chartsData = reactive({
      completedData: [],
      closeData: [],
      allData: [],
      orderTotal: {}
    })
    const formState = reactive({
      employeeLeaderId: null,
      employeeId: null
    })
    const leaderList = ref([])
    const systemUserList = ref([])
    const collectionActiveKey = ref('today')
    const amountActiveKey = ref('today')
    const collectionTableData = ref([])
    const amountTableData = ref([])
    const myChart = {}

    function collectionChange(value) {
      collectionActiveKey.value = value
      if (value === 'today') {
        getInsertToday()
      } else {
        getInsertHistory()
      }
    }

    function amountChange(value) {
      amountActiveKey.value = value
      if (value === 'today') {
        getIncomeToday()
      } else {
        getIncomeHistory()
      }
    }

    async function getAllOrderNum() {
      const res = await fetchOrderNum(formState)
      console.log(res)
      if (res.code === 1) {
        const {
          backlogNum,
          emphasisNum,
          todoNumHistory,
          todoNumInsert,
          insertNum,
          historyNum,
          closeNumHistory,
          closeNumInsert,
          totalNum,
          todoNum,
          closeNum
        } = res.data
        chartsData.completedData = [
          {value: todoNumInsert, name: t('今日新增')},
          {value: todoNumHistory, name: t('历史库存')},
        ]
        chartsData.closeData = [
          {value: closeNumInsert, name: t('今日新增')},
          {value: closeNumHistory, name: t('历史库存')},
        ]
        chartsData.allData = [
          {value: insertNum, name: t('今日新增')},
          {value: historyNum, name: t('历史库存')},
        ]
        chartsData.orderTotal = {totalNum, closeNum, todoNum, backlogNum, emphasisNum}
        initCharts('order_charts1', chartsData.completedData)
        initCharts('order_charts2', chartsData.closeData)
        initCharts('order_charts3', chartsData.allData)
      }
    }

    // 历史收款单数
    async function getInsertHistory() {
      const res = await fetchInsertHistory(formState)
      if (res.code === 1) {
        collectionTableData.value = [res.data]
      }
    }

    // 今日收款单数
    async function getInsertToday() {
      const res = await fetchInsertToday(formState)
      if (res.code === 1) {
        collectionTableData.value = [res.data]
      }
    }

    // 历史收款金额数
    async function getIncomeHistory() {
      const res = await fetchIncomeHistory(formState)
      if (res.code === 1) {
        amountTableData.value = [res.data]
      }
    }

    // 今日收款金额数
    async function getIncomeToday() {
      const res = await fetchIncomeToday(formState)
      if (res.code === 1) {
        amountTableData.value = [res.data]
      }
    }

    function initCharts(el, data) {
      myChart[el] = echarts.init(document.getElementById(el));
      myChart[el].setOption({
        tooltip: {
          trigger: 'item'
        },
        legend: {
          top: '5%',
          left: 'center'
        },
        series: [
          {
            type: 'pie',
            radius: '50%',
            labelLine: {
              show: false
            },
            label: {
              show: false,
              position: 'center'
            },
            data: data,
            emphasis: {
              itemStyle: {
                shadowBlur: 10,
                shadowOffsetX: 0,
                shadowColor: 'rgba(0, 0, 0, 0.5)'
              }
            }
          }
        ]
      });
    }

    function handleFinish() {
      getAllOrderNum()
      collectionChange(collectionActiveKey.value)
      amountChange(amountActiveKey.value)
    }

    function isPermission(value) {
      return hasPermission('Index', value)
    }

    function changeLeader(value) {
      selectHomeSystemUser({systemId: value}).then(res => {
        formState.employeeId = null
        systemUserList.value = res.data
      })
    }

    function getReSize() {
      myChart.order_charts1.resize()
      myChart.order_charts2.resize()
      myChart.order_charts3.resize()
    }

    onMounted(() => {
      getAllOrderNum()
      getInsertToday()
      getIncomeToday()
      if (isPermission('leader')) {
        selectLeader().then(res => {
          leaderList.value = res.data
        })
      }
      if (isPermission('user')) {
        selectHomeSystemUser().then(res => {
          systemUserList.value = res.data
        })
      }
      window.addEventListener('resize', getReSize)
    })
    onBeforeUnmount(() => {
      window.removeEventListener('resize', getReSize)
    })
    return {
      collectionTabList,
      collectionActiveKey,
      amountActiveKey,
      amountChange,
      amountTableData,
      collectionChange,
      collectionTableColumn,
      amountTableColumn,
      collectionTableData,
      systemUserList,
      leaderList,
      formState,
      handleFinish,
      isPermission,
      changeLeader,
      ...toRefs(chartsData),
    }
  }
}
</script>

<style lang="less" scoped>
//.charts {
//  display: grid;
//  grid-template-columns: 1fr 1fr 1fr;
//  grid-gap: 2%;
//}

.order_charts {
  width: 100%;
  height: 300px;
}
</style>
